<template>
  <div class="query-container">
    <!-- 查询 -->
    <el-input
        placeholder="用户姓名"
        v-model="queryName"
        class="query-input"
        clearable
        @clear="getallUsers"
    ></el-input>
    <el-button @click="queryByName" type="success" plain class="query-button">查询</el-button>
    <el-button @click="showUserDialog" type="primary" class="add-button">添加</el-button>
  </div>

  <!-- 错误消息 -->
  <div class="error-message">{{ errorMessage }}</div>

  <!-- 用户列表 -->
  <el-table :data="userList" style="width: 100%" border class="custom-table">
    <el-table-column label="序号" prop="id" width="60px"></el-table-column>
    <el-table-column prop="nickname" label="姓名" width="80px"></el-table-column>
    <el-table-column prop="sex" label="性别" width="80px">
      <template #default="scope">{{ scope.row.sex === 0 ? '女' : '男' }}</template>
    </el-table-column>
    <el-table-column prop="roleId" label="员工类别" width="80px">
      <template #default="scope">
        {{ getRoleLabel(scope.row.roleId) }}
      </template>
    </el-table-column>
    <el-table-column prop="email" label="邮箱" width="100px"></el-table-column>
    <el-table-column prop="phoneNumber" label="联系电话" width="120px"></el-table-column>
    <el-table-column prop="createTime" label="入职时间" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="updateTime" label="操作时间" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="updateBy" label="人员状态" width="80px">
      <template #default="scope">{{ scope.row.state === 0 ? '在职' : '离职' }}</template>
    </el-table-column>
    <el-table-column label="操作" width="150px">
      <template #default="scope">
        <el-button type="primary" size="small" @click="showEditDialog(scope.row.id)">修改</el-button>
        <el-button type="danger" size="small" @click="confirmDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination
        background
        v-model:current-page="pageContains.pageNum"
        v-model:page-size="pageContains.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageContains.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />
  </div>

  <!-- 添加/编辑用户对话框 -->
  <el-dialog v-model="userDialog" :title="dialogTitle" width="40%" class="custom-dialog">
    <el-form :model="curUser" label-width="80px" class="custom-form">
      <el-form-item label="用户姓名" class="form-item">
        <el-input v-model="curUser.nickname" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="用户名" class="form-item">
        <el-input v-model="curUser.username" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="性别" class="form-item">
        <el-select v-model="curUser.sex" key="sex" class="form-input">
          <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="员工类别" class="form-item">
        <el-select v-model="curUser.roleId" key="roleId" class="form-input">
          <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" class="form-item">
        <el-input v-model="curUser.email" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" class="form-item">
        <el-input v-model="curUser.phoneNumber" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="入职时间" class="form-item">
        <el-date-picker v-model="curUser.createTime" class="form-input"></el-date-picker>
      </el-form-item>
    </el-form>
    <el-button @click="optOne" type="primary" class="dialog-footer-button">{{ buttonOpt }}</el-button>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import http from '@/axios/http';
import { debounce } from 'lodash';
import dayjs from 'dayjs';
import qs from 'qs';
import { ElMessage, ElMessageBox } from "element-plus";

// 数据
let userList = ref([]);
let errorMessage = ref('');
let queryName = ref('');
let userDialog = ref(false);
let curUser = ref({
  nickname: '',
  username: '',
  sex: null,
  roleId: null,
  email: '',
  phoneNumber: '',
  createTime: null
});
let sexOptions = [{ label: '女', value: 0 }, { label: '男', value: 1 }];
let roleOptions = [
  { label: '管理员', value: 1 },
  { label: '健康管家', value: 2 },
  { label: '医生', value: 3 },
  { label: '护工', value: 4 }
];
let dialogTitle = reactive('');
let buttonOpt = reactive('');
let dialogOptType = reactive('');
let pageNum = 1;
let pageSize = 10;
let size = 10;

// 当前页码信息
let pageContains = ref({});

// 初始化
onMounted(() => {
  getallUsers();
});

function getallUsers() {
  let params = {
    size: size,
    pageNum: pageNum,
    pageSize: pageSize
  };

  http.post('/lyy/get_all_users', params).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      userList.value = result.data.list;
    } else {
      showError(result.error);
    }
  });
}

function formatDate(row, column) {
  const date = row[column.property];
  return date ? dayjs(date).format('YYYY-MM-DD') : '';
}

const debouncedQueryByName = debounce(() => {
  let param = { nickname: queryName.value };
  http.post('/lyy/get_users_by', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      userList.value = result.data;
    } else {
      showError(result.error);
    }
  });
}, 500);

function queryByName() {
  debouncedQueryByName();
}

function showUserDialog() {
  // 初始化
  curUser.value = {
    nickname: '',
    username: '',
    sex: null,
    roleId: null,
    email: '',
    phoneNumber: '',
    createTime: null
  };
  userDialog.value = true;
  dialogTitle = '用户信息录入';
  buttonOpt = '录入';
  dialogOptType = 2;
}

function showEditDialog(id) {
  // 初始化
  curUser.value = {};
  userDialog.value = true;
  dialogTitle = '用户信息修改';
  buttonOpt = '修改';
  dialogOptType = 1;
  getUserInfo(id);
}

function getUserInfo(id) {
  let param = {
    id: id
  };
  http.post('/lyy/get_user_by', qs.stringify(param)).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      curUser.value = result.data;
    } else {
      showError(result.error);
    }
  });
}

function confirmDelete(id) {
  ElMessageBox.confirm('是否确认删除该用户？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(id);
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
}

function deleteUser(id) {
  let param = {
    id: id
  };
  http.post('/lyy/delete_userbyid', qs.stringify(param)).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      getallUsers();
      ElMessage.success('删除成功');
    } else {
      showError(result.error);
    }
  });
}

function recordOne() {
  if (!curUser.value.username) {
    showError('用户名不能为空');
    return;
  }
  curUser.value.password = curUser.value.username;
  http.post('/lyy/add_one_user', curUser.value).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      userDialog.value = false;
      getallUsers();
      ElMessage.success('录入成功');
    } else {
      showError(result.error);
    }
  });
}

function editOne() {
  http.post('/lyy/update_one_user', curUser.value).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      userDialog.value = false;
      ElMessage.success('修改成功');
      getallUsers();

    } else {
      showError(result.error);
    }
  });
}

function optOne() {
  if (dialogOptType === 2) {
    recordOne();
  } else if (dialogOptType === 1) {
    editOne();
  }
}

function showError(message) {
  errorMessage.value = message;
  setTimeout(() => {
    errorMessage.value = '';
  }, 3000);
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageNum = pageNum1;
  getallUsers();
};

const handleSizeChange = (pageSize1) => {
  pageSize = pageSize1;
  getallUsers();
};

const getRoleLabel = (roleId) => {
  const role = roleOptions.find((item) => item.value === roleId);
  return role ? role.label : '未知';
};
</script>

<style scoped>
/* 查询区域 */
.query-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.query-input {
  width: 250px;
  margin-right: 10px;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
}

.query-button {
  margin-right: 10px;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 14px;
}

.add-button {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 16px;
  background-color: #409eff;
  color: white;
}

/* 错误消息 */
.error-message {
  color: red;
  margin-bottom: 10px;
  text-align: center;
}

/* 表格样式 */
.custom-table {
  font-size: 14px;
  margin-top: 10px;
  border-radius: 4px;
  overflow: hidden;
}

.custom-table td,
.custom-table th {
  padding: 8px 0;
  text-align: center;
}

.custom-table .el-table__header th {
  background-color: #f5f7fa;
  color: #333;
}

/* 对话框样式 */
.custom-dialog {
  border-radius: 8px;
}

.custom-dialog .el-dialog__body {
  padding: 20px;
}

.custom-form {
  max-width: 500px;
  margin: 0 auto;
}

.form-item {
  margin-bottom: 15px;
}

.form-label {
  font-weight: bold;
  font-size: 14px;
}

.form-input {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-footer-button {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 4px;
  background-color: #409eff;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .query-input {
    width: 180px;
  }

  .add-button {
    font-size: 14px;
  }

  .custom-table {
    font-size: 12px;
  }

  .form-input {
    height: 36px;
  }
}
</style>